package com.example.tomatotodo.ui;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.tomatotodo.R;
import com.example.tomatotodo.model.TodoConstants;
import com.example.tomatotodo.model.TodoItem;
import com.example.tomatotodo.model.TodoSettingDTO;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class AddTodoDialog extends Dialog {

    private static final String TAG = "AddTodoDialog";
    private LinearLayout addCardTopBar;
    private TextView btnSave, btnClose; // 保存按钮、关闭按钮
    private ImageView btnRefresh; // 刷新按钮
    private EditText todoInput; // 待办名称输入框
    private Button btnNormal, btnGoal; // 普通番茄钟按钮、定目标按钮
    private Button btnDeadLine; // 截止日期按钮
    private EditText valueEditText;
    private Button unitButton;
    private String[] units = {"小时", "分钟", "次"};
    private int currentUnitIndex = 0;
    private Button btnCountdown, btnForward, btnNoTimer; // 倒计时按钮、正向计时按钮、不计时按钮
    private Button btn25min, btn35min, btnCustom; // （仅限倒计时）25分钟按钮、35分钟按钮、自定义按钮
    private LinearLayout layoutTimerMode, layoutTimeOptions;
    private LinearLayout line3, line4;
    private EditText line8, line9;

    private int customTime = 25; // 自定义时间，默认25分钟

    private boolean isNormalSelected = true;
    private boolean isCountdownSelected = true; // 倒计时按钮是否被选中

    private Calendar deadLine; // 截止日期变量

    // 新增编辑模式相关变量
    private boolean isEdit = false;
    private TodoItem editTodoItem;
    private int currentColor; // 当前颜色

    public interface OnTodoItemAddedListener {
        void onTodoItemAdded(TodoItem newItem);
    }

    private OnTodoItemAddedListener listener;

    public AddTodoDialog(Context context, OnTodoItemAddedListener listener) {
        super(context);
        this.listener = listener;
    }

    // 新增构造函数，用于编辑模式
    public AddTodoDialog(Context context, OnTodoItemAddedListener listener, TodoItem editTodoItem) {
        super(context);
        this.listener = listener;
        this.isEdit = true;
        this.editTodoItem = editTodoItem;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_todo, null);
        setContentView(view);

        deadLine = Calendar.getInstance();

        // 绑定控件
        addCardTopBar = view.findViewById(R.id.add_card_top_bar);

        todoInput = view.findViewById(R.id.todo_input);
        btnNormal = view.findViewById(R.id.btn_normal);
        btnGoal = view.findViewById(R.id.btn_goal);
        btnRefresh = view.findViewById(R.id.btn_refresh);
        btnSave = view.findViewById(R.id.btn_save);
        btnClose = view.findViewById(R.id.btn_close);

        line3 = view.findViewById(R.id.line3);
        btnDeadLine = view.findViewById(R.id.btn_dead_line);

        line4 = view.findViewById(R.id.line4);
        valueEditText = findViewById(R.id.valueEditText);
        unitButton = findViewById(R.id.unitButton);

        layoutTimerMode = view.findViewById(R.id.layout_timer_mode);
        btnCountdown = view.findViewById(R.id.btn_countdown);
        btnForward = view.findViewById(R.id.btn_forward);
        btnNoTimer = view.findViewById(R.id.btn_no_timer);

        layoutTimeOptions = view.findViewById(R.id.layout_time_options);
        btn25min = view.findViewById(R.id.btn_25min);
        btn35min = view.findViewById(R.id.btn_35min);
        btnCustom = view.findViewById(R.id.btn_custom);

        line8 = view.findViewById(R.id.line8); // 循环次数输入框
        line9 = view.findViewById(R.id.line9); // 自定义休息时间输入框

        // 默认状态
        setButtonSelected(true);
        setTimerModeSelected(btnCountdown);
        setTimeOptionSelected(btn25min);
        if (isEdit) {
            TextView dialogTitle = view.findViewById(R.id.dialog_title);
            dialogTitle.setText("编辑待办");
            currentColor = editTodoItem.getColor();
        } else {
            currentColor = new TodoItem(new com.example.tomatotodo.model.TodoSettingDTO()).getColor();
        }
        addCardTopBar.setBackgroundColor(currentColor);
        Log.d(TAG, "onCreate: 添加Todo窗口初始化完成");

        Log.d(TAG, "onCreate: isEdit = " + isEdit);

        // 如果是编辑模式，加载待办事项数据
        if (isEdit && editTodoItem != null) {
            Log.d(TAG, "onCreate: 加载待办事项数据");
            loadTodoItemData();
        }

        // 按钮点击切换
        btnNormal.setOnClickListener(v -> {
            Log.d(TAG, "onCreate: 点击了普通番茄钟按钮");
            setButtonSelected(true);
            todoInput.setHint("请输入待办名称");
        });

        btnGoal.setOnClickListener(v -> {
            Log.d(TAG, "onCreate: 点击了定目标按钮");
            setButtonSelected(false);
            todoInput.setHint("请输入目标名称");
        });

        // 第3行按钮
        btnDeadLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
            }
        });

        // 第4行按钮，设置单位按钮点击事件
        unitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchUnit();
            }
        });

        // 第4行按钮，设置文本框焦点变化监听
        valueEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    // 失去焦点时记录日志
                    logValueAndUnit();
                }
            }
        });

        // 第6行按钮
        btnCountdown.setOnClickListener(v -> {
            setTimerModeSelected(btnCountdown);
            layoutTimeOptions.setVisibility(View.VISIBLE);
        });

        btnForward.setOnClickListener(v -> {
            setTimerModeSelected(btnForward);
            layoutTimeOptions.setVisibility(View.GONE);
            // 隐藏循环次数输入框
            line8.setVisibility(View.GONE);
        });

        btnNoTimer.setOnClickListener(v -> {
            setTimerModeSelected(btnNoTimer);
            layoutTimeOptions.setVisibility(View.GONE);
            // 隐藏循环次数和自定义休息时间输入框
            line8.setVisibility(View.GONE);
            line9.setVisibility(View.GONE);
        });

        // 第7行按钮
        btn25min.setOnClickListener(v -> setTimeOptionSelected(btn25min));
        btn35min.setOnClickListener(v -> setTimeOptionSelected(btn35min));
        btnCustom.setOnClickListener(v -> {
            if (isCountdownSelected) {
                showCustomTimeDialog();
            } else {
                setTimeOptionSelected(btnCustom);
            }
        });

        // 刷新按钮, 改变颜色
        btnRefresh.setOnClickListener(v -> {
            // 如果是编辑模式，则随机切换颜色（标题栏部分背景颜色跟着变化）
            // 如果不是编辑模式，则先生成颜色，背景颜色变化，临时存储颜色，最后存到TodoItem里
            currentColor = new TodoItem(new TodoSettingDTO()).getColor();
            // 更新标题栏背景颜色
            addCardTopBar.setBackgroundColor(currentColor);
        });

        // 保存按钮
        btnSave.setOnClickListener(v -> {
            saveTodoItem();
            dismiss();
        });

        // 关闭按钮
        btnClose.setOnClickListener(v -> dismiss());
    }

    /**
     * 设置【普通番茄钟】按钮选中
     */
    private void setButtonSelected(boolean normalSelected) {
        isNormalSelected = normalSelected;
        if (normalSelected) { // 普通番茄钟
            btnNormal.setBackgroundResource(R.drawable.bg_button_normal);
            btnNormal.setTextColor(getContext().getResources().getColor(android.R.color.holo_blue_light));

            btnGoal.setBackgroundResource(R.drawable.bg_button_unselected);
            btnGoal.setTextColor(0xFF555555);

            line3.setVisibility(View.GONE);
            line4.setVisibility(View.GONE);
        } else { // 定目标
            btnGoal.setBackgroundResource(R.drawable.bg_button_normal);
            btnGoal.setTextColor(getContext().getResources().getColor(android.R.color.holo_blue_light));

            btnNormal.setBackgroundResource(R.drawable.bg_button_unselected);
            btnNormal.setTextColor(0xFF555555);

            line3.setVisibility(View.VISIBLE);
            line4.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 设置计时模式按钮选中
     */
    private void setTimerModeSelected(Button selectedButton) {
        btnCountdown.setBackgroundResource(R.drawable.bg_button_unselected_small);
        btnCountdown.setTextColor(0xFF555555);
        btnForward.setBackgroundResource(R.drawable.bg_button_unselected_small);
        btnForward.setTextColor(0xFF555555);
        btnNoTimer.setBackgroundResource(R.drawable.bg_button_unselected_small);
        btnNoTimer.setTextColor(0xFF555555);

        selectedButton.setBackgroundResource(R.drawable.bg_button_normal_small);
        selectedButton.setTextColor(getContext().getResources().getColor(android.R.color.holo_blue_light));

        isCountdownSelected = (selectedButton == btnCountdown);

        // 根据选中的按钮显示/隐藏相应的输入框
        if (selectedButton == btnCountdown) {
            // 倒计时模式：显示所有输入框
            line8.setVisibility(View.VISIBLE);
            line9.setVisibility(View.VISIBLE);
        } else if (selectedButton == btnForward) {
            // 正向计时模式：只隐藏循环次数输入框
            line8.setVisibility(View.GONE);
            line9.setVisibility(View.VISIBLE);
        } else if (selectedButton == btnNoTimer) {
            // 不计时模式：隐藏循环次数和自定义休息时间输入框
            line8.setVisibility(View.GONE);
            line9.setVisibility(View.GONE);
        }
    }

    /**
     * 设置时间选项按钮选中
     */
    private void setTimeOptionSelected(Button selectedButton) {
        btn25min.setBackgroundResource(R.drawable.bg_button_unselected_small);
        btn25min.setTextColor(0xFF555555);
        btn35min.setBackgroundResource(R.drawable.bg_button_unselected_small);
        btn35min.setTextColor(0xFF555555);
        btnCustom.setBackgroundResource(R.drawable.bg_button_unselected_small);
        btnCustom.setTextColor(0xFF555555);

        selectedButton.setBackgroundResource(R.drawable.bg_button_normal_small);
        selectedButton.setTextColor(getContext().getResources().getColor(android.R.color.holo_blue_light));

        // 更新自定义按钮文本
        if (selectedButton == btnCustom) {
            btnCustom.setText(customTime + "分钟");
        }
    }

    /**
     * 显示日期选择器对话框
     */
    private void showDatePickerDialog() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this.getContext(),
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        deadLine.set(Calendar.YEAR, year);
                        deadLine.set(Calendar.MONTH, month);
                        deadLine.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        updateDateButtonText();
                        Log.d(TAG, "onDateSet: deadLine对应时间戳为: " + deadLine.getTimeInMillis());
                    }
                },
                deadLine.get(Calendar.YEAR),
                deadLine.get(Calendar.MONTH),
                deadLine.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    /**
     * 更新截止日期按钮的文本
     */
    private void updateDateButtonText() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        String formattedDate = sdf.format(deadLine.getTime());
        btnDeadLine.setText(formattedDate);
    }

    private void switchUnit() {
        // 循环切换单位
        currentUnitIndex = (currentUnitIndex + 1) % units.length;
        unitButton.setText(units[currentUnitIndex]);

        // 记录单位切换日志
        Log.d(TAG, "Unit switched to: " + units[currentUnitIndex]);
    }

    private void logValueAndUnit() {
        String value = valueEditText.getText().toString();
        String unit = units[currentUnitIndex];

        if (!value.isEmpty()) {
            Log.d(TAG, "Value: " + value + ", Unit: " + unit);
        } else {
            Log.d(TAG, "Value is empty, Unit: " + unit);
        }
    }

    /**
     * 显示自定义时间设置弹窗
     */
    private void showCustomTimeDialog() {
        // 创建弹窗
        Dialog customTimeDialog = new Dialog(getContext());
        customTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_custom_time, null);
        customTimeDialog.setContentView(view);

        // 获取控件
        EditText customTimeInput = view.findViewById(R.id.custom_time_input);
        Button btnCancel = view.findViewById(R.id.btn_cancel);
        Button btnConfirm = view.findViewById(R.id.btn_confirm);

        // 设置默认值
        customTimeInput.setText(String.valueOf(customTime));
        customTimeInput.setSelection(customTimeInput.getText().length());
        customTimeInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});

        // 设置取消按钮点击事件
        btnCancel.setOnClickListener(v -> customTimeDialog.dismiss());

        // 设置确定按钮点击事件
        btnConfirm.setOnClickListener(v -> {
            String input = customTimeInput.getText().toString();
            if (!input.isEmpty()) {
                try {
                    int time = Integer.parseInt(input);
                    if (time > 0) {
                        customTime = time;
                        btnCustom.setText(customTime + "分钟");
                        setTimeOptionSelected(btnCustom);
                        customTimeDialog.dismiss();
                    } else {
                        // 输入值无效，显示错误提示
                        android.widget.Toast.makeText(getContext(), "请输入大于0的数字", android.widget.Toast.LENGTH_SHORT).show();
                    }
                } catch (NumberFormatException e) {
                    // 输入值无效，显示错误提示
                    android.widget.Toast.makeText(getContext(), "请输入有效的数字", android.widget.Toast.LENGTH_SHORT).show();
                }
            } else {
                // 输入为空，显示错误提示
                android.widget.Toast.makeText(getContext(), "请输入时间", android.widget.Toast.LENGTH_SHORT).show();
            }
        });

        // 显示弹窗
        customTimeDialog.show();
    }

    /**
     * 加载待办事项数据到界面（编辑模式）
     */
    private void loadTodoItemData() {
        if (editTodoItem == null) return;

        TodoSettingDTO setting = editTodoItem.getSetting();
        if (setting == null) return;

        // 设置标题
        if (setting.getTitle() != null) {
            todoInput.setText(setting.getTitle());
        }

        // 设置类型
        if (TodoConstants.TYPE_GOAL.equals(setting.getType())) {
            setButtonSelected(false);
            todoInput.setHint("请输入目标名称");
        } else {
            setButtonSelected(true);
            todoInput.setHint("请输入待办名称");
        }

        // 设置截止日期（如果是目标类型）
        if (setting.getGoalDeadline() != null && !setting.getGoalDeadline().isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                deadLine.setTime(sdf.parse(setting.getGoalDeadline()));
                updateDateButtonText();
            } catch (Exception e) {
                Log.e(TAG, "Failed to parse deadline date", e);
            }
        }

        // 设置目标值和单位（如果是目标类型）
        if (setting.getGoalTargetValue() != null && setting.getGoalTargetType() != null) {
            if (TodoConstants.GOAL_TARGET_TYPE_DURATION.equals(setting.getGoalTargetType())) {
                int seconds = setting.getGoalTargetValue();
                if (seconds % 3600 == 0) { // 小时
                    valueEditText.setText(String.valueOf(seconds / 3600));
                    currentUnitIndex = 0;
                } else { // 分钟
                    valueEditText.setText(String.valueOf(seconds / 60));
                    currentUnitIndex = 1;
                }
            } else if (TodoConstants.GOAL_TARGET_TYPE_TIMES.equals(setting.getGoalTargetType())) {
                valueEditText.setText(String.valueOf(setting.getGoalTargetValue()));
                currentUnitIndex = 2;
            }
            unitButton.setText(units[currentUnitIndex]);
        }

        // 设置计时模式
        if (TodoConstants.TIMER_MODE_COUNTDOWN.equals(setting.getTimerMode())) {
            setTimerModeSelected(btnCountdown);
            layoutTimeOptions.setVisibility(View.VISIBLE);
        } else if (TodoConstants.TIMER_MODE_UPTIME.equals(setting.getTimerMode())) {
            setTimerModeSelected(btnForward);
            layoutTimeOptions.setVisibility(View.GONE);
        } else if (TodoConstants.TIMER_MODE_NO_TIMER.equals(setting.getTimerMode())) {
            setTimerModeSelected(btnNoTimer);
            layoutTimeOptions.setVisibility(View.GONE);
        }

        // 设置倒计时时长
        if (setting.getCountdownDuration() != null) {
            int durationInMinutes = setting.getCountdownDuration() / 60;
            if (durationInMinutes == 25) {
                setTimeOptionSelected(btn25min);
            } else if (durationInMinutes == 35) {
                setTimeOptionSelected(btn35min);
            } else {
                customTime = durationInMinutes;
                btnCustom.setText(customTime + "分钟");
                setTimeOptionSelected(btnCustom);
            }
        }

        // 设置循环次数
        if (setting.getCycle() != null) {
            line8.setText(String.valueOf(setting.getCycle()));
        }

        // 设置休息时长
        if (setting.getRestDuration() != null) {
            int restInMinutes = setting.getRestDuration() / 60;
            line9.setText(String.valueOf(restInMinutes));
        }
    }

    /**
     * 保存待办事项
     */
    private void saveTodoItem() {
        // 创建TodoSettingDTO对象
        TodoSettingDTO setting = new TodoSettingDTO();

        // 设置标题
        String title = todoInput.getText().toString();
        
        // 验证标题不为空
        if (title.isEmpty()) {
            android.widget.Toast.makeText(getContext(), "请输入待办名称", android.widget.Toast.LENGTH_SHORT).show();
            return;
        }
        setting.setTitle(title);

        // 设置类型（普通番茄钟或定目标）
        String type = isNormalSelected ? TodoConstants.TYPE_POMODORO : TodoConstants.TYPE_GOAL;
        setting.setType(type);

        // 设置计时模式
        String timerMode = "";
        if (btnCountdown.getCurrentTextColor() == getContext().getResources().getColor(android.R.color.holo_blue_light)) {
            timerMode = TodoConstants.TIMER_MODE_COUNTDOWN;
        } else if (btnForward.getCurrentTextColor() == getContext().getResources().getColor(android.R.color.holo_blue_light)) {
            timerMode = TodoConstants.TIMER_MODE_UPTIME;
        } else if (btnNoTimer.getCurrentTextColor() == getContext().getResources().getColor(android.R.color.holo_blue_light)) {
            timerMode = TodoConstants.TIMER_MODE_NO_TIMER;
        }
        setting.setTimerMode(timerMode);

        // 设置倒计时时长
        if (btn25min.getCurrentTextColor() == getContext().getResources().getColor(android.R.color.holo_blue_light)) {
            setting.setCountdownDuration(25 * 60); // 25分钟
        } else if (btn35min.getCurrentTextColor() == getContext().getResources().getColor(android.R.color.holo_blue_light)) {
            setting.setCountdownDuration(35 * 60); // 35分钟
        } else if (btnCustom.getCurrentTextColor() == getContext().getResources().getColor(android.R.color.holo_blue_light)) {
            // 验证自定义时间大于0
            if (customTime <= 0) {
                android.widget.Toast.makeText(getContext(), "倒计时时间必须大于0分钟", android.widget.Toast.LENGTH_SHORT).show();
                return;
            }
            setting.setCountdownDuration(customTime * 60); // 自定义时间（分钟转秒）
        }

        // 如果是定目标类型，设置目标相关信息
        if (!isNormalSelected) {
            // 设置截止日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            setting.setGoalDeadline(sdf.format(deadLine.getTime()));

            // 设置目标类型和值
            String goalValue = valueEditText.getText().toString();
            if (!goalValue.isEmpty()) {
                int goalValueInt = Integer.parseInt(goalValue);
                
                // 验证目标值大于0
                if (goalValueInt <= 0) {
                    android.widget.Toast.makeText(getContext(), "目标值必须大于0", android.widget.Toast.LENGTH_SHORT).show();
                    return;
                }
                
                setting.setGoalTargetValue(goalValueInt);

                String goalType = "";
                switch (currentUnitIndex) {
                    case 0: // 小时
                        goalType = TodoConstants.GOAL_TARGET_TYPE_DURATION;
                        // 转换为秒
                        setting.setGoalTargetValue(Integer.parseInt(goalValue) * 3600);
                        break;
                    case 1: // 分钟
                        goalType = TodoConstants.GOAL_TARGET_TYPE_DURATION;
                        // 转换为秒
                        setting.setGoalTargetValue(Integer.parseInt(goalValue) * 60);
                        break;
                    case 2: // 次
                        goalType = TodoConstants.GOAL_TARGET_TYPE_TIMES;
                        break;
                }
                setting.setGoalTargetType(goalType);
            } else {
                // 如果目标值为空，显示错误提示
                android.widget.Toast.makeText(getContext(), "请输入目标值", android.widget.Toast.LENGTH_SHORT).show();
                return;
            }
        }

        // 设置循环次数
        String cycleText = line8.getText().toString();
        if (!cycleText.isEmpty()) {
            setting.setCycle(Integer.parseInt(cycleText));
        } else {
            setting.setCycle(1); // 默认值
        }

        // 如果是正向计时模式，则循环次数强制设置为1
        if (TodoConstants.TIMER_MODE_UPTIME.equals(timerMode)) {
            setting.setCycle(1);
        }

        // 设置休息时长
        String restText = line9.getText().toString();
        if (!restText.isEmpty()) {
            setting.setRestDuration(Integer.parseInt(restText) * 60); // 分钟转秒
        } else {
            setting.setRestDuration(5 * 60); // 默认5分钟
        }

        // 创建TodoItem对象
        TodoItem todoItem;
        todoItem = new TodoItem(setting, currentColor);

        // 使用Gson将对象转换为JSON
        Gson gson = new Gson();
        String json = gson.toJson(todoItem);

        // 通过Log.d输出JSON数据
        Log.d(TAG, "Saved TodoItem JSON: " + json);

        // 如果有监听器，通知数据已添加
        if (listener != null) {
            listener.onTodoItemAdded(todoItem);
        }
    }
}